package com.guaju.yueshangLife.fragment.goods;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.BuyActivity;
import com.guaju.yueshangLife.activity.GetCouponListDialogActivity;
import com.guaju.yueshangLife.activity.GoodsDetailActivity;
import com.guaju.yueshangLife.base.GoodsDetail;
import com.guaju.yueshangLife.bean.TagsBean;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.imageloader.BannerFrescoImageLoader;
import com.guaju.yueshangLife.utils.Utils;
import com.guaju.yueshangLife.utils.WebViewUtil;
import com.guaju.yueshangLife.widget.GoodsDetailTag;
import com.youth.banner.Banner;
import com.ysnows.page.Page;
import com.ysnows.page.PageBehavior;
import com.ysnows.page.PageContainer;
import com.zhy.autolayout.AutoLinearLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class GoodsDetailFragment extends Fragment implements PageBehavior.OnPageChanged {

    public static final String GOOD_DATA = "good_data";
    public static final int SELECT_OPTION = 1001;
    private static final int COUPON = 1010;
    private WebView webview;
    private Banner banner;
    private ArrayList<String> list = new ArrayList<>();
    private ArrayList<String> bannerLists = new ArrayList<>();
    private Page pageOne;
    private PageContainer container;
    private Page.OnScrollListener onScrollListener;
    private View content_detail;
    private View bottom_container;
    private GoodsDetailActivity goodsDetailActivity;
    private TextView price_now;
    private TextView price_old;
    private TextView tag_sale;
    private TextView tag_hot;
    private TextView tag_time;
    private TextView goods_dec;
    private TextView tag_sale_address;
    private TextView tag_sale_count;
    private TextView tag_sale_left_nums;
    private TextView tag_zhiliang;
    private TextView tag_baoyou;
    private TextView tag_changjia;
    private RelativeLayout rl_select_option;
    private RelativeLayout rl_size_sheet;
    private RelativeLayout rl_youhui;
    private TextView tv_youhui_content;
    private TextView comment_amount;
    private TextView tv_view_all_comment;
    private AutoLinearLayout ll_goods_detail_tag_container;
    public static int tooglePosition = 0;
    //数据
    private GoodsDetail.DataBean goodsDetailData;
    private View view;
    private View news_loading;
    private RelativeLayout rl_container;

    public GoodsDetailFragment() {
        // Required empty public constructor
        //
    }

    private static GoodsDetailFragment fragment = null;

    public static GoodsDetailFragment newInstance() {
        if (fragment == null) {
            fragment = new GoodsDetailFragment();
        }
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_goods_detail_with_customview, container, false);
        goodsDetailActivity = (GoodsDetailActivity) getActivity();
        initView(view);

        setListener();

        return view;

    }

    private void setListener() {
        rl_select_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出buy窗口
                Intent intent = new Intent(getActivity(), BuyActivity.class);
                BaseApplication.getInstance().setCurrentGoodDetail(goodsDetailData);
                getActivity().startActivityForResult(intent, SELECT_OPTION);
            }
        });
        rl_youhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GetCouponListDialogActivity.class);
                getActivity().startActivityForResult(intent, COUPON);
            }
        });


    }

    private void initView(View view) {
        Banner banner = view.findViewById(R.id.banner);
        View goods_info = view.findViewById(R.id.goods_info);
        content_detail = view.findViewById(R.id.content_detail);
        rl_container = view.findViewById(R.id.rl_container);

        ll_goods_detail_tag_container = goods_info.findViewById(R.id.ll_goods_detail_tag_container);
        price_now = goods_info.findViewById(R.id.price_now);
        price_old = goods_info.findViewById(R.id.price_old);
        tag_sale = goods_info.findViewById(R.id.tag_sale);
        tag_hot = goods_info.findViewById(R.id.tag_hot);
        tag_time = goods_info.findViewById(R.id.tag_time);
        goods_dec = goods_info.findViewById(R.id.goods_dec);
        tag_sale_address = goods_info.findViewById(R.id.tag_sale_address);
        tag_sale_count = goods_info.findViewById(R.id.tag_sale_count);
        tag_sale_left_nums = goods_info.findViewById(R.id.tag_sale_left_nums);
        tag_zhiliang = goods_info.findViewById(R.id.tag_zhiliang);
        tag_baoyou = goods_info.findViewById(R.id.tag_baoyou);
        tag_changjia = goods_info.findViewById(R.id.tag_changjia);

        rl_select_option = goods_info.findViewById(R.id.rl_select_option);
        rl_size_sheet = goods_info.findViewById(R.id.rl_size_sheet);
        rl_youhui = goods_info.findViewById(R.id.rl_youhui);

        tv_youhui_content = goods_info.findViewById(R.id.tv_youhui_content);
        comment_amount = goods_info.findViewById(R.id.comment_amount);
        tv_view_all_comment = goods_info.findViewById(R.id.tv_view_all_comment);

        addProgressPic();

    }

    private void addProgressPic() {
        news_loading = View.inflate(getActivity(), R.layout.loading, null);
        news_loading.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, 0, 0));
        Bitmap mBgBitmap = Utils.readBitMap(getActivity(), R.drawable.good_detail_loadding);
        news_loading.setBackgroundDrawable(new BitmapDrawable(mBgBitmap));
        rl_container.addView(news_loading);
        news_loading.setVisibility(View.VISIBLE);
        goodsDetailActivity.binding.goodsError.setVisibility(View.GONE);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        banner = (Banner) view.findViewById(R.id.banner);
        pageOne = (Page) view.findViewById(R.id.pageOne);
        container = (PageContainer) view.findViewById(R.id.container);


        bottom_container = view.findViewById(R.id.bottom_container);

        bottom_container.setVisibility(View.INVISIBLE);

        pageOne.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY < oldScrollY) {
                    Log.e("=====", "上滑");
                    goodsDetailActivity.binding.goodsTopBar.setVisibility(View.VISIBLE);
                }

                if (scrollY == 0) {
                    Log.e("=====", "滑倒顶部");
                    goodsDetailActivity.binding.goodsTopBar.setVisibility(View.INVISIBLE);
                } else if (scrollY > 0) {
                    goodsDetailActivity.binding.goodsTopBar.setVisibility(View.VISIBLE);
                }


            }
        });

        container.setOnPageChanged(new PageBehavior.OnPageChanged() {
            @Override
            public void toTop() {
                //位于第一页
                bottom_container.setVisibility(View.INVISIBLE);
                goodsDetailActivity.binding.goodsTopBar.setCurrentTab(0);
                goodsDetailActivity.binding.goodsTopBar.setVisibility(View.INVISIBLE);
                tooglePosition = 0;
            }

            @Override
            public void toBottom() {
                //位于第二页
                bottom_container.setVisibility(View.VISIBLE);
                goodsDetailActivity.binding.goodsTopBar.setCurrentTab(1);
                goodsDetailActivity.binding.goodsTopBar.setVisibility(View.VISIBLE);
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) content_detail.getLayoutParams();
                layoutParams.topMargin = goodsDetailActivity.binding.goodsTopBar.getHeight();
                content_detail.setLayoutParams(layoutParams);
                tooglePosition = 1;
            }
        });

    }


    boolean isTop = true;

    public void toggle() {
        if (isTop) {
            container.scrollToBottom();
            bottom_container.setVisibility(View.INVISIBLE);
        } else {
            isTop = true;
            container.backToTop();
            bottom_container.setVisibility(View.VISIBLE);
        }
    }

    public void toggleInt() {
        if (1 == this.tooglePosition) {
            container.scrollToBottom();
            bottom_container.setVisibility(View.VISIBLE);
            goodsDetailActivity.binding.goodsTopBar.setVisibility(View.VISIBLE);
            this.tooglePosition = 0;
        } else {
            isTop = true;
            container.backToTop();
            bottom_container.setVisibility(View.INVISIBLE);
            goodsDetailActivity.binding.goodsTopBar.setVisibility(View.INVISIBLE);
            this.tooglePosition = 1;
        }
    }


    public void toggleToTop() {
        isTop = true;
        tooglePosition = 0;
        container.backToTop();
        bottom_container.setVisibility(View.VISIBLE);

    }

    public void toggleToButtom() {
        tooglePosition = 1;
        container.scrollToBottom();
        bottom_container.setVisibility(View.INVISIBLE);

    }

    @Override
    public void toTop() {
        isTop = true;
//        Toast.makeText(getContext(), "Top", Toast.LENGTH_SHORT).show();
        goodsDetailActivity.binding.goodsTopBar.setCurrentTab(0);
        tooglePosition = 0;
    }

    @Override
    public void toBottom() {
        isTop = false;
//        Toast.makeText(getContext(), "Bottom", Toast.LENGTH_SHORT).show();
        goodsDetailActivity.binding.goodsTopBar.setCurrentTab(1);
        tooglePosition = 1;
    }

    public void updateView(GoodsDetail goodsDetail) {
        goodsDetailData = goodsDetail.getData();
        //banner


        List<GoodsDetail.DataBean.ImagesBean> images = goodsDetailData.getImages();
        bannerLists.clear();
        for (GoodsDetail.DataBean.ImagesBean imagesBean : images) {
            bannerLists.add(imagesBean.getHost() + "/"+imagesBean.getPath());
        }

        BannerFrescoImageLoader frescoImageLoader = new BannerFrescoImageLoader();
        if (banner==null){
            banner=(Banner) view.findViewById(R.id.banner);
        }
        banner.setImageLoader(frescoImageLoader);
        banner.setImages(bannerLists);
        banner.start();
        // price
        price_now.setText("¥" + goodsDetailData.getPrice().getCurrent());
        price_old.setText("¥" + goodsDetailData.getPrice().getOriginal());
        // tags
        List<TagsBean> tags = goodsDetailData.getTags();
        for (TagsBean tagsBean : tags) {
            GoodsDetailTag goodsDetailTag = new GoodsDetailTag(getActivity());
            goodsDetailTag.setTagName(tagsBean.getName());
            ll_goods_detail_tag_container.addView(goodsDetailTag);
        }

        //名称
        String name = goodsDetailData.getName();
        goods_dec.setText(name);

        //销售量 94
        int count_sales = goodsDetailData.getCount_sales();
        tag_sale_count.setText("月销 " + count_sales + " 件");

        List<GoodsDetail.DataBean.SkuBean> sku = goodsDetailData.getSku();
        int totalLeftNum=0;
        for (GoodsDetail.DataBean.SkuBean skuBean:sku) {
            totalLeftNum+=skuBean.getStock();
        }
        tag_sale_left_nums.setText("库存 "+totalLeftNum+" 件");

        String summary = goodsDetailData.getSummary();
        initWebview(summary);
        news_loading.setVisibility(View.GONE);
        goodsDetailActivity.binding.buyBottom.getRoot().setVisibility(View.VISIBLE);

    }

    private void initWebview(String summary) {
        WebView webview = content_detail.findViewById(R.id.webview);
        final WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        WebViewUtil.loadData(webview, summary);
    }

}
